package service;

import application.MyLogger;
import application.MySession;
import dao.inte.UserRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Calendar;
import java.util.logging.Logger;

@Singleton
@Transactional
public class LoggerServiceImpl implements ILoggerService {
    private static Logger logger = Logger.getLogger(LoggerServiceImpl.class.getName());

    @Inject
    private MyLogger myLogger;
    @Inject
    private UserRepository userRepository;
    @Inject
    private MySession mySession;

    public LoggerServiceImpl() {
    }

    public LoggerServiceImpl(MyLogger myLogger, UserRepository userRepository, MySession mySession) {
        this.myLogger = myLogger;
        this.userRepository = userRepository;
        this.mySession = mySession;
    }

    public void log(ActionType actionType) {
        MyLogger.ActionType action = resolveAction(actionType);
        String userLogin = null;
        try {
            userLogin = userRepository.findById(mySession.getId()).getLogin();
        } catch (IllegalStateException e) {
            //hopefully for tests only
            userLogin = "UNKNOWN";
        }
        myLogger.log(Calendar.getInstance().getTime(), userLogin, action);
    }

    private MyLogger.ActionType resolveAction(ActionType actionType) {
        switch (actionType) {
            case CHANGE_SETTINGS:
                return MyLogger.ActionType.CHANGE_SETTINGS;
            case ORDER_SENDED:
                return MyLogger.ActionType.ORDER_SENDED;
            case PASSWORD_CHANGE_REQUEST:
                return MyLogger.ActionType.PASSWORD_CHANGE_REQUEST;
            case USER_LOGGED:
                return MyLogger.ActionType.USER_LOGGED;
            default:
                logger.info("Error in LoggerServiceImpl - 34");
                break;
        }
        return null;
    }

}
